package com.yanqu.road.server.manager.strongholdwar;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.tradewar.CrossTradeWarActivityMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CrossStrongholdChatMgr extends TempMgr {

    public static final int MAX_MESSAGE_COUNT = 50;

    private static Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder> chatMsgMap;

    @Override
    public boolean reloadData() {
        chatMsgMap = new ConcurrentHashMap<>();
        return true;
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void activityChat(int activityId, WorldMessageProto.WorldMessageTempMsg chatMsg){
        ActivityInfo activityInfo = CrossTradeWarActivityMgr.getActivityInfo(activityId);
        if(!ActivityHelper.activityInShowTime(activityInfo)){
            return;
        }
        if(!chatMsgMap.containsKey(activityId)){
            synchronized (chatMsgMap){
                if(!chatMsgMap.containsKey(activityId)){
                    chatMsgMap.put(activityId, WorldMessageProto.WorldMessageListMsg.newBuilder());
                }
            }
        }
        WorldMessageProto.WorldMessageListMsg.Builder chatListMsg = chatMsgMap.get(activityId);
        synchronized (chatListMsg){
            if(chatListMsg.getDataListCount() >= MAX_MESSAGE_COUNT){
                chatListMsg.removeDataList(0);
            }
            chatListMsg.addDataList(chatMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.A_WORLD_MESSAGE_TRANSFER, chatMsg);
        for(long serverId : activityInfo.getServerIdList()){
            MessageHelper.sendPacket(serverId, 0, pbMsg);
        }
    }

    public static WorldMessageProto.WorldMessageListMsg.Builder getChatListMsg(int activityId){
        return chatMsgMap.get(activityId);
    }
}
